package me.zhengjie.modules.security.rest;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.gas.model.ResponseDto;
import me.zhengjie.gas.service.ACEService;
import me.zhengjie.modules.security.service.MobileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Api(tags = "油站：用戶登錄兼容")
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class MobileController {

	@Autowired
	private ACEService aceService;

	@Autowired
	private MobileService mobileService;

	@ApiOperation("手機APP掃碼登錄")
	@PostMapping("/mobileLogin")
	public ResponseDto mobileLogin(@RequestBody Map<String, Object> params,
	                               HttpServletRequest request) {
		String encrypted = (String) params.get("encrypted");
		String decrypted = aceService.decrypt(encrypted);
		if (StringUtils.isEmpty(decrypted)) {
			//throw new RuntimeException("登录失败!");
			return new ResponseDto(-100, "登录失败!");
		}

		ObjectMapper objectMapper = new ObjectMapper();
		try {
			Map<String, Object> map = objectMapper.readValue(decrypted, new TypeReference<Map<String, Object>>() {});
			String userName = (String) map.get("userName");
			String password = (String) map.get("password");
			//String deviceId = (String) map.get("deviceId");
			return mobileService.mobileLogin(userName, password, request);
		} catch (JsonProcessingException e) {
			return new ResponseDto(-101, e.getMessage());
		}
	}

	@ApiOperation("創建移動設備登錄賬戶")
	@GetMapping("/genMobileAccount")
	public ResponseDto genMobileAccount(@RequestParam("deptId") Long deptId) {
		return mobileService.generateMobileAccount(deptId);
	}
}
